package com.sam.chat;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


/**
 * 打印请求和响应信息
 */
@Aspect
@Component
@Log4j2
public class LogAspect {
    //拿到日志对象
//    slf4j的日志对象
    @Pointcut("execution(public * com.sam.chat.controller.*.*(..))")
    public void webLog() {

    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws IOException {
        //收到请求,记录请求内容
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

     /*   //记录请求url
        log.info("http-url: " + request.getRequestURL().toString());
        //记录请求方法
        log.info("http-method: " + request.getMethod());
        //记录请求IP
        log.info("http-Ip: " + request.getRemoteAddr());
        //获取类的信息
        log.info("http-Class: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //参数信息
        log.info("http-Params: " + request.getQueryString());*/

        log.info("--->" + request.getRequestURL().toString() + "\n"
                + request.getMethod() + "\n"
                + request.getRemoteAddr() + "\n"
                + request.getQueryString()
        );

      /*  //获取请求body
        byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
        String body = new String(bodyBytes, request.getCharacterEncoding());
        log.info("http-body: "+body);*/
    }

    @AfterReturning(returning = "res", pointcut = "webLog()")
    public void doAfterReturning(Object res) throws JsonProcessingException {
        //处理完请求，返回内容
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("--->"
                + request.getRequestURL().toString() + "\n"
                + new ObjectMapper().writeValueAsString(res));
    }
}
